package com.aflac.proxy.cglib;

import java.lang.reflect.Method;
import java.util.Arrays;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

// CGLIB动态代理
// 1. 首先实现一个MethodInterceptor，方法调用会被转发到该类的intercept()方法。
class MyMethodInterceptor implements MethodInterceptor {
	@Override
	public Object intercept(Object obj, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		System.out.println("You said: " + Arrays.toString(args));
		//System.out.println(obj);
		
		System.out.println(method.getName());
		return proxy.invokeSuper(obj, args);
	}

	public static void main(String[] args) {
		// 2. 然后在需要使用HelloConcrete的时候，通过CGLIB动态代理获取代理对象。
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(HelloConcrete.class);
		enhancer.setCallback(new MyMethodInterceptor());

		HelloConcrete hello = (HelloConcrete) enhancer.create();
		//System.out.println(hello);System.out.println(hello.getClass().getCanonicalName());
		System.out.println(hello.getClass().getSuperclass());
		//System.out.println(hello.getClass().getTypeName());
		System.out.println();
		for (Method method : hello.getClass().getMethods()) {
			System.out.println(method.getName());
		}
		hello.sayHello("I love you!");
	}
}